<template>
  <div>
    <!--搜索表单-->
    <div style="margin: 10px 0">
      <el-input prefix-icon="el-icon-user" style="width: 240px;" placeholder="请输入用户名"
                v-model="params.username"></el-input>
      <el-input prefix-icon="el-icon-phone-outline" style="width: 240px;margin-left: 5px" placeholder="请输入联系方式"
                v-model="params.phone"></el-input>
      <el-input prefix-icon="el-icon-postcard" style="width: 240px;margin-left: 5px" placeholder="请输入邮箱"
                v-model="params.email"></el-input>
      <el-button style="margin-left: 5px" type="primary" @click="load"><i class="el-icon-search"></i>搜索</el-button>
      <el-button style="margin-left: 5px" type="warning" @click="reset"><i class="el-icon-refresh"></i>重置</el-button>
    </div>

    <!--数据表格-->
    <el-table :data="tableDate" stripe>
      <el-table-column prop="id" label="编号" width="60px"></el-table-column>
      <el-table-column prop="username" label="用户名"></el-table-column>
      <el-table-column prop="phone" label="联系方式"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="createTime" label="创建时间"></el-table-column>
      <el-table-column prop="updateTime" label="更新时间"></el-table-column>

      <el-table-column label="状态">
        <template v-slot="scope">
          <el-switch
              v-model="scope.row.status"
              @change="changeStatus(scope.row)"
              active-color="#13ce66"
              inactive-color="#dfdfdf">
          </el-switch>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="260px">
        <template v-slot="scope">

          <!--scope.row就是当前行的数据-->
          <el-button style="margin-right: 5px" type="primary" @click="$router.push('/editAdmin?id='+scope.row.id)">
            编辑
          </el-button>

          <template>
            <el-popconfirm title="您确定删除这行数据吗？" @confirm="del(scope.row.id)">
              <el-button slot="reference" type="danger">删除</el-button>
            </el-popconfirm>
            <el-button style="margin-left: 5px" type="warning" @click="handelChangePassword(scope.row)">
              修改密码
            </el-button>
          </template>

        </template>
      </el-table-column>
    </el-table>

    <!--分页-->
    <div style="margin-top: 10px">
      <el-pagination
          background
          :current-page="params.pageNum"
          :page-size="params.pageSize"
          layout="prev, pager, next"
          @current-change="handleCurrentChange"
          :total="total">
      </el-pagination>
    </div>

    <!--修改密码的表单-->
    <el-dialog title="修改密码" :visible.sync="dialogFormVisible" width="30%">
      <el-form :model="form" label-width="80px" ref="formRef" :rules="rules">
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="form.newPassword" autocomplete="off" show-password></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="savePassword">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import request from "@/utils/request";
import Cookies from "js-cookie";

export default {
  name: 'Admin',
  data() {
    return {
      tableDate: [],       //1.存放数据
      total: 0,           //总条数
      form: {},
      dialogFormVisible: false, //默认不打开
      params: {            //分页模糊查询参数
        pageSize: 10,
        pageNum: 1,
        username: '',
        phone: '',
        email: ''
      },
      rules: {
        newPassword: [
          {required: true, message: '密码不能为空', trigger: 'blur'},
          {required: true, message: '长度在 3 到 10 个字符', trigger: 'blur'}
        ],
      },
      admin: Cookies.get('admin') ? JSON.parse(Cookies.get('admin')) : {}
    }
  },
  created() {					//3.前端页面加载数据
    this.load()
  },
  methods: {
    load() {                 //2.请求后台数据
      request.get('/admin/page', {
        params: this.params
      }).then(res => {
        console.log(res.data)
        if (res.code === '200') {
          this.tableDate = res.data.list
          this.total = res.data.total
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    reset() {               //重置搜索框数据
      this.params = {
        pageSize: 10,
        pageNum: 1,
        username: '',
        phone: '',
        email: ''
      }
      this.load()
    },
    handleCurrentChange(pageNum) {      //点击分页按钮触发分页
      this.params.pageNum = pageNum
      this.load()
    },
    del(id) {     //删除管理员信息
      request.delete("/admin/delete/" + id).then(res => {
        if (res.code === '200') {
          this.$notify.success("删除成功")
          this.load()
        } else {
          this.$notify.error("删除失败" + res.msg)
        }
      })
    },
    handelChangePassword(row) {   //修改密码
      this.form = JSON.parse(JSON.stringify(row))
      this.dialogFormVisible = true     //打开弹窗
    },
    changeStatus(row) {    //更改状态
      if (this.admin.id === row.id && !row.status) {
        row.status = true
        this.$notify.warning("不能更改自己的状态")
        return
      }
      request.put('/admin/update', row).then(res => {
        if (res.code === '200') {
          this.$notify.success('操作成功！')
          this.load()
        } else {
          this.$notify.error('操作失败！' + res.msg)
        }
      })
    },
    savePassword() { //修改密码
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          request.put('/admin/updatePassword', this.form).then(res => {
            if (res.code === '200') {
              this.$notify.success("修改成功")
              if (this.form.id === this.admin.id) {   //当前修改密码的用户id等于当前登陆的管理员id，那么修改成功之后需要重新登陆
                Cookies.remove('admin')
                this.$router.push('/login')
              }
              this.dialogFormVisible = false
            } else {
              this.$notify.error("修改失败")
            }
          })
        }
      })
    }
  }
}
</script>